import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "../assets/css/cart.css";
import { List, SwipeAction } from "antd-mobile";

// 调取购物车的接口
import { cartList, delCart } from "../request/api";

function Cart() {
  // 删除
  let [rightActions] = useState([
    { key: "delete", text: "删除", color: "danger" },
  ]);
  // 购物车列表
  let [cartlist, setcartlist] = useState([]);
  // 万人团
  let [cartlist1, setcartlist1] = useState([]);
  // 全选
  let [allCheck, changeAll] = useState(false);
  // 万人团全选
  let [allCheck1, changeAll1] = useState(false);
  // 其他全选
  let [allCheck2, changeAll2] = useState(false);
  // 总价
  let [allPrice, changePrice] = useState(0);

  useEffect(() => {
    cartList({ uid: JSON.parse(sessionStorage.getItem("isLogin")).uid }).then(
      (res) => {
        console.log(res, "购物车列表");
        if (res.code == 200) {
          setcartlist(res.list[1].content || []);
          setcartlist1(res.list[0].content || []);
          // console.log(cartlist);
          // console.log(cartlist1);
        }
      }
    );
  }, []);
  useEffect(() => {
    // 总价
    function price() {
      let sum1 = 0; // 万人团
      let sum2 = 0; // 其他
      let sum = 0; // 总计

      cartlist.map((item) => {
        // console.log(item);
        // console.log(item.isCheck);
        if (item.isCheck) {
          sum1 += item.price * item.num;
        }
      });
      cartlist1.map((item) => {
        if (item.isCheck) {
          sum2 += item.price * item.num;
        }
      });
      sum = sum1 + sum2;
      return sum.toFixed(2);
    }
    changePrice(price);

    if (allCheck1 && allCheck2) {
      changeAll(allCheck2);
    } else {
      changeAll(false);
    }
  });

  // 数量++
  function add(i) {
    // console.log(i, "下标");
    cartlist[i].num++;
    setcartlist([...cartlist]);
  }

  // 万人团数量++
  function add1(i) {
    // console.log(i, "下标");
    cartlist1[i].num++;
    setcartlist1([...cartlist1]);
  }

  // 数量--
  function desc(i) {
    // console.log(i, "下标");
    if (cartlist[i].num <= 1) {
      cartlist[i].num = 1;
    } else {
      cartlist[i].num--;
    }
    setcartlist([...cartlist]);
  }

  // 万人团数量--
  function desc1(i) {
    // console.log(i, "下标");
    if (cartlist1[i].num <= 1) {
      cartlist1[i].num = 1;
    } else {
      cartlist1[i].num--;
    }
    setcartlist1([...cartlist1]);
  }

  // 万人团全选
  function checkAll1() {
    changeAll1(!allCheck1);
    // changeAll((allCheck = !allCheck1));
    cartlist1.map((item) => {
      item.isCheck = !allCheck1;
    });
    setcartlist1([...cartlist1]);
  }

  // 其他全选
  function checkAll2() {
    changeAll2(!allCheck2);
    // changeAll((allCheck = !allCheck2));
    cartlist.map((item) => {
      item.isCheck = !allCheck2;
    });
    setcartlist([...cartlist]);
  }

  // 万人团单选控全选
  function changeOne1(i) {
    // console.log(i);
    cartlist1[i].isCheck = !cartlist1[i].isCheck;
    let tag = cartlist1.every((item) => item.isCheck);
    // console.log(tag);
    changeAll1(tag);
    changeAll(tag);
    setcartlist1([...cartlist1]);
  }

  // 其他单选控全选
  function changeOne(i) {
    // console.log(i);
    cartlist[i].isCheck = !cartlist[i].isCheck;
    let tag = cartlist.every((item) => item.isCheck);
    // console.log(tag);
    changeAll2(tag);
    changeAll(tag);
    setcartlist([...cartlist]);
  }

  // 全选控单选
  function checkAll() {
    changeAll(!allCheck);
    changeAll1((allCheck1 = !allCheck));
    changeAll2((allCheck2 = !allCheck));
    cartlist1.map((item) => {
      item.isCheck = !allCheck;
    });
    cartlist.map((item) => {
      item.isCheck = !allCheck;
    });
    setcartlist([...cartlist]);
    setcartlist1([...cartlist1]);
  }

  // 删除
  function del(id) {
    delCart({ id }).then((res) => {
      console.log(res);
      if (res.code == 200) {
        cartList({
          uid: JSON.parse(sessionStorage.getItem("isLogin")).uid,
        }).then((res) => {
          console.log(res, "购物车列表");
          if (res.code == 200) {
            setcartlist(res.list[1].content || []);
            setcartlist1(res.list[0].content || []);
          }
        });
      }
    });
  }

  // 结算
  function submit(e) {
    let arr = []; //总计
    let arr1 = []; //万人团
    let arr2 = []; //其他

    let num = 0; //总计
    let num1 = 0; //万人团
    let num2 = 0; //其他

    let val = ""; //总计
    let val1 = ""; //万人团
    let val2 = ""; //其他
    cartlist.map((item) => {
      if (item.isCheck) {
        num1 += item.num;
        arr1.push(item);
        val1 += `,${item.id}`;
      }
    });
    cartlist1.map((item) => {
      if (item.isCheck) {
        num2 += item.num;
        arr2.push(item);
        val2 += `,${item.id}`;
      }
    });
    num = num1 + num2;
    val = val1 + val2;

    let orderInfo = {
      countmoney: allPrice,
      countnumber: num,
      idstr: val.slice(1),
    };
    arr = arr1.concat(arr2);
    if (num) {
      // 将订单信息存到存储中
      sessionStorage.setItem("orderInfo", JSON.stringify(orderInfo));
      //   // 将选中的购物车列表数组存到存储中
      sessionStorage.setItem("arr", JSON.stringify(arr));
    } else {
      e.preventDefault();
      alert("至少选择一件商品");
    }
  }

  return (
    <div id="cart">
      <header>
        {/* 顶部信息  */}
        <div className="top_box">
          <h2>购物车</h2>
        </div>
        <div className="header_box">
          {/* 推荐 */}
          <div className="recommend">
            <ul>
              <li>
                <a href="">全部(20)</a>
              </li>
              <li>
                <a href="">降价(4)</a>
              </li>
              <li>
                <a href="">常卖(2)</a>
              </li>
              <li>
                <a href="">分类</a>
                <span className="iconfont icon-jiage"></span>
              </li>
            </ul>
          </div>
        </div>
      </header>
      {/* 小u自营  */}
      {cartlist1.length > 0 && (
        <div className="ziying">
          <div className="left">
            <input
              type="checkbox"
              className="tui-checkbox"
              onChange={() => checkAll1()}
              checked={allCheck1 || ""}
            />
            <span>万人团</span>
          </div>
          <div className="right">
            <span>已免运费</span>
            <span>领券</span>
          </div>
        </div>
      )}
      {cartlist1.length > 0 && (
        <List className="ziying_bot">
          {cartlist1.map((item, i) => {
            return (
              <SwipeAction
                rightActions={rightActions}
                key={item.id}
                onAction={() => del(item.id)}
              >
                <List.Item>
                  <div className="cont">
                    <div className="left">
                      <input
                        type="checkbox"
                        className="tui-checkbox"
                        onChange={() => changeOne1(i)}
                        checked={item.isCheck || ""}
                      />
                      <img src={item.img} alt="" />
                    </div>
                    <div className="right">
                      <p>{item.goodsname}</p>
                      <p>敏感肌可用，控油祛痘、男女可...</p>
                      <p>
                        <select>
                          <option value="粉色 50ML">粉色 50ML</option>
                        </select>
                      </p>
                      <p>比加入时降低￥100</p>
                      <div className="box">
                        <div className="price">
                          <span>￥</span>
                          <span>{item.price}</span>
                          <del>￥1099</del>
                        </div>
                        <div className="amount">
                          <span onClick={() => desc1(i)}>-</span>
                          <span>{item.num}</span>
                          <span onClick={() => add1(i)}>+</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </List.Item>
              </SwipeAction>
            );
          })}
        </List>
      )}
      {cartlist.length > 0 && (
        <div className="ziying top">
          <div className="left">
            <input
              type="checkbox"
              className="tui-checkbox"
              onChange={() => checkAll2()}
              checked={allCheck2 || ""}
            />
            <span>其他</span>
          </div>
          <div className="right">
            <span>已免运费</span>
            <span>领券</span>
          </div>
        </div>
      )}
      {cartlist.length > 0 && (
        <List className="ziying_bot  bot1">
          {cartlist.map((item, i) => {
            return (
              <SwipeAction
                rightActions={rightActions}
                key={item.id}
                onAction={() => del(item.id)}
              >
                <List.Item>
                  <div className="cont">
                    <div className="left">
                      <input
                        type="checkbox"
                        className="tui-checkbox"
                        onChange={() => changeOne(i)}
                        checked={item.isCheck || ""}
                      />
                      <img src={item.img} alt="" />
                    </div>
                    <div className="right">
                      <p>{item.goodsname}</p>
                      <p>敏感肌可用，控油祛痘、男女可...</p>
                      <p>
                        <select>
                          <option value="粉色 50ML">粉色 50ML</option>
                        </select>
                      </p>
                      <p>比加入时降低￥100</p>
                      <div className="box">
                        <div className="price">
                          <span>￥</span>
                          <span>{item.price}</span>
                          <del>￥1099</del>
                        </div>
                        <div className="amount">
                          <span onClick={() => desc(i)}>-</span>
                          <span>{item.num}</span>
                          <span onClick={() => add(i)}>+</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </List.Item>
              </SwipeAction>
            );
          })}
        </List>
      )}
      {cartlist1.length == 0 && cartlist.length == 0 && (
        <div className="shop">
          <h2>购物车空空如也，快去买买买！！！</h2>
        </div>
      )}
      <div className="footer">
        <div>
          <input
            type="checkbox"
            className="tui-checkbox"
            onChange={() => checkAll()}
            checked={allCheck || ""}
          />
          <span>全选</span>
        </div>
        <div>
          <span>合计</span>
          <span>已免运费</span>
        </div>
        <div>
          <span>￥{allPrice}</span>
          <span>已优惠￥200元</span>
        </div>
        <Link to="/order" onClick={(e) => submit(e)} className="submit">
          结算
        </Link>
      </div>
    </div>
  );
}

export default Cart;
